#include "httpmgr.h"
#include<QNetworkReply>
#include<toast.h>
HttpMgr::HttpMgr() {
    QObject::connect(this,&HttpMgr::sig_http_finish,this,&HttpMgr::slot_http_finish);
}
void HttpMgr::PostHttpReq(QUrl url,QJsonObject json,ReqId id,MoudleId mid){
    QByteArray data=QJsonDocument(json).toJson();

    //设置url和请求报文
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    request.setHeader(QNetworkRequest::ContentLengthHeader,QByteArray::number(data.length()));

    //发送post报文
    auto self=shared_from_this();
    QNetworkReply *reply=m_qnetworkmgr.post(request,data);

    QObject::connect(reply,&QNetworkReply::finished,[self,reply,id,mid](){
        //处理错误信息
        if(reply->error()!=QNetworkReply::NoError){
            qDebug()<<reply->errorString();
            //Toast::error(reply->errorString());
            //结束请求结束
            emit self->sig_http_finish(id,Ecode::ERROR_JSON,mid,"");
            reply->deleteLater();
            return;
        }


        auto res=reply->readAll();
        qDebug()<<res;
        emit self->sig_http_finish(id,Ecode::SUCCESS,mid,res);
        reply->deleteLater();
    });
}

void HttpMgr::slot_http_finish(ReqId id,Ecode error,MoudleId mid,QString res){
    switch (mid) {
    case MoudleId::REGISTER:{
        emit sig_reg_http_finish(id,res,error);
    }break;

    case MoudleId::RESETPSW:{
        emit sig_resetpsw_http_finish(id,res,error);
    }break;

    case MoudleId::LOGIN:{
        emit sig_login_http_finish(id,res,error);
    }
    default:
        break;
    }
}
